#!/usr/bin/env bash
# 文件名: check_go2_env.sh  （Debian + python3.9 实测通过）
set -euo pipefail

RED='\033[31m'; GREEN='\033[32m'; NC='\033[0m'
log_info()  { echo -e "${GREEN}[INFO]${NC} $*"; }
log_error() { echo -e "${RED}[ERROR]${NC} $*"; }
exit_fail() { log_error "Go2 环境检查未通过！"; exit 1; }
exit_ok()   { log_info  "Go2 环境已就绪！"; exit 0; }

# -------------- 1. 找到 Python ≥ 3.8 --------------
locate_python() {
    [[ -n "${PYTHON_CMD:-}" ]] && \
        { verify_python_version "$PYTHON_CMD" && return 0; } || true

    for cmd in python3.11 python3.10 python3.9 python3.8 python3; do
        command -v "$cmd" &>/dev/null || continue
        verify_python_version "$cmd" && return 0
    done
    log_error "未找到 Python ≥ 3.8"; return 1
}

verify_python_version() {
    local py="$1"
    local ver_str major
    ver_str=$("$py" --version 2>&1)          # "Python 3.9.16"
    major=${ver_str#Python }; major=${major%.*}
    if awk -v v="$major" 'BEGIN{exit !(v >= 3.8)}'; then
        export PYTHON_CMD="$py"
        log_info "Python 版本: $major (符合 ≥3.8)"
        return 0
    else
        log_error "$py 版本 $major 低于 3.8"; return 1
    fi
}

# -------------- 2. 检查 pip 包 --------------
verify_pip_pkg() {
    local pkg_spec=$1
    local pkg_name=${pkg_spec%%[=<>!]*}
    log_info "检测 pip 包: $pkg_spec"

    # 把变量写进去，避免 here-doc 拿不到
    "$PYTHON_CMD" - "$pkg_name" "$pkg_spec" <<'EOF'
import sys, importlib.metadata as im
pkg_name, pkg_spec = sys.argv[1], sys.argv[2]
try:
    installed = im.version(pkg_name)
    if "==" not in pkg_spec:
        print(f"[OK] {pkg_name} 已安装（任意版本: {installed}）")
    else:
        required = pkg_spec.split("==")[1]
        if installed == required:
            print(f"[OK] {pkg_spec} 已安装")
        else:
            print(f"[FAIL] 版本不匹配: 需要 {required}, 实际 {installed}")
            sys.exit(1)
except im.PackageNotFoundError:
    print(f"[FAIL] {pkg_name} 未安装")
    sys.exit(1)
EOF
}

# -------------- 主流程 --------------
main() {
    locate_python || exit_fail

    FAIL=0
    verify_pip_pkg "cyclonedds==0.10.2" || FAIL=1
    verify_pip_pkg "numpy"               || FAIL=1
    verify_pip_pkg "opencv-python"       || FAIL=1

    [ $FAIL -eq 0 ] && exit_ok || exit_fail
}

main "$@"